/* eslint-disable */
import Vue from 'vue'
import Vuex from 'vuex'
import api from '../API/index'
import router from '../router/index'

const defaultAvatar = new Image('../../static/img/default-avatar.png')
Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    shop: {},
    token: window.localStorage.token || ''
    // token: ''
  },
  mutations: {
    setShop(state, data) {
      if (!data.avatar) {
        data.avatar = defaultAvatar
      }
      state.shop = data
    },
    setToken(state, token) {
      state.token = token
    }
  },
  actions: {
    login({ commit, state }, payload) {
      api.LOGIN(payload).then(({ data }) => {
        if (data.status === 200) {
          commit('setShop', data.data.shopDetail)
          commit('setToken', data.data.token)
          window.localStorage.token = data.data.token
          window.localStorage.shopId = data.data.shopDetail.shopId
          router.push('/manage/goods')
        }
      })
    },
    checkToken({ commit, state }, payload) {
      return api
        .CHECK_TOKEN()
        .then(({ data }) => {
          if (data.status === 200) {
            commit('setShop', data.data.shop)
            return data
            // router.replace('/manage')
          }
        })
        .catch(() => {})
    }
  }
})

export default store
